package com.it.flowable.util;

import org.flowable.bpmn.model.ExtensionAttribute;
import org.flowable.bpmn.model.ExtensionElement;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ExtensionElementUtils {


    /**
     * <pre>
     * <userTask id="leaderApproval" name="直属领导审批" flowable:assignee="${leaderAssignee}">
     *     <extensionElements>
     *         <flowable:notify notifyType="assign" templateId="001"/>
     *         <flowable:notify notifyType="full" templateId="002"/>
     *     </extensionElements>
     * </userTask>
     * </pre>
     * <p>
     */
    public static ExtensionElement createExtensionElement(Map<String, String> attrMap, String field) {

        ExtensionElement extensionElement = new ExtensionElement();
        extensionElement.setNamespace("http://flowable.org/bpmn");
        extensionElement.setNamespacePrefix("flowable");
        extensionElement.setName(field);

        List<ExtensionAttribute> list = attrMap.entrySet()
                .stream()
                .map((entry) -> createExtensionAttribute(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());
        List<ExtensionAttribute> exist = extensionElement.getAttributes().get(field);
        if (exist != null) {
            exist.addAll(list);
        } else {
            extensionElement.getAttributes().put(field, list);
        }
        return extensionElement;
    }

    public static ExtensionAttribute createExtensionAttribute(String name, String value) {
        ExtensionAttribute valueAttr = new ExtensionAttribute(name);
        valueAttr.setValue(value);
        return valueAttr;
    }
}
